package cn.edu.lingnan.controllerV1;

import cn.edu.lingnan.service.ExamService;
import cn.edu.lingnan.user.dtos.*;
import cn.edu.lingnan.user.pojos.Exam;
import cn.edu.lingnan.user.pojos.PageBean;
import cn.edu.lingnan.user.vos.ExamPaperDetailVo;
import cn.edu.lingnan.user.vos.ExamScoreVO;
import cn.edu.lingnan.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/exam")
@Slf4j
public class ExamController {
    @Autowired
    private ExamService examService;


    /**
     * 获取考试列表，分页查询
     *
     * @return
     */
    @PostMapping("/examList")
    public Result<?> getExamList(@RequestBody ListExamDto listExamDto) {
        log.info("获取考试列表，分页查询");
        PageBean<?> pageBean = examService.getExamList(listExamDto);
        return Result.success(pageBean);
    }

    //新增考试
    @PostMapping("/addExam")
    public Result<?> addExam(@RequestBody Exam exam) {
        log.info("新增考试");
        examService.addExam(exam);
        return Result.success();
    }

    //删除考试
    @DeleteMapping("/deleteExam")
    public Result<?> deleteExam(@RequestParam("examId") Integer examId) {
        log.info("删除考试");
        Integer flag = examService.deleteExam(examId);
        if (flag == 0) {
            return Result.error("正在考试中，不能删除！");
        }
        if (flag == -1) {
            return Result.error("该考试存在已交卷的考生，不能删除！");
        }
        if (flag == -2) {
            return Result.error("考试已发布，不能删除！");
        }
        return Result.success();
    }


    //查询考生分页

    @PostMapping("/getExamUser")
    public Result<?> getExamUser(@RequestBody ListUserExam listUserExam) {
        log.info("查询考生,分页查询");
        PageBean<?> pageBean = examService.getExamUser(listUserExam);
        return Result.success(pageBean);
    }

    //根据考试id查询考试信息
    @GetMapping("/getExamById")
    public Result<?> getExamById(@RequestParam("examId") Integer examId) {
        log.info("根据考试id查询考试信息");
        Exam exam = examService.getExamById(examId);
        return Result.success(exam);
    }

    //修改考试信息
    @PostMapping("/updateExam")
    public Result<?> updateExam(@RequestBody Exam exam) {
        log.info("修改考试信息");
        examService.updateExam(exam);
        return Result.success();
    }

    //添加考试考生
    @PostMapping("/addExamUser")
    public Result<?> addExamUser(@RequestBody AddExamUserDto addExamUserDto) {
        try {
            int flag = examService.addExamUser(addExamUserDto);
            if (flag == 1) {
                return Result.success("添加考生成功");
            } else if (flag == -1) {
                return Result.error("截止时间不能早于开始时间");
            } else if (flag == 0) {
                return Result.error("考试不处于未发布状态");
            } else if (flag == -2) {
                return Result.error("考试时间有误，请检查");
            } else {
                return Result.error("未知错误");
            }
        } catch (Exception e) {
            // Log the exception
            return Result.error("添加考生失败: " + e.getMessage());
        }
    }

    //发布考试
    @PutMapping("/publishExam")
    public Result<?> publishExam(@RequestParam("examId") Integer examId) {
        examService.publishExam(examId);
        return Result.success();

    }

    //修改考试状态
    @PutMapping("/updateExamStatus")
    public Result<?> updateExamStatus(@RequestParam("examId") Integer examId, @RequestParam("status") Integer status) {
        examService.updateExamStatus(examId, status);
        return Result.success("修改成功");
    }

    //参加考试
    @PutMapping("/joinExam")
    public Result<?> joinExam(@RequestParam("examId") Integer examId) {
        Integer flag = examService.joinExam(examId);
        if (flag == -1) {
            return Result.error("您已迟到，无法参加考试，请联系老师");
        }
        if (flag == -2) {
            return Result.error("考试还未开始，无法参加考试");
        }
        return Result.success("参加成功");
    }


    //查询考试试卷
    @GetMapping("/getExamingPaperById")
    public Result<ExamPaperDetailVo> getExamingPaperById(@RequestParam("examId") Integer examId) {
        return examService.getExamingPaperById(examId);
    }


    //交卷
    @PostMapping("/submit")
    public Result<String> submitExam(@RequestBody SubmitExamDTO submitExamDTO) {
        try {
            examService.processExamSubmission(submitExamDTO);
            log.info("考试提交,{}", submitExamDTO);
            return Result.success("考试提交成功");
        } catch (Exception e) {
            return Result.error("考试提交失败：" + e.getMessage());
        }
    }


    // 查询用户的考试记录
    @GetMapping("/scores")
    public Result<PageBean<ExamScoreVO>> getUserExamScores(
            @RequestHeader("Authorization") String token, // 从请求头中获取 JWT
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        try {
            // 1. 提取 JWT
            if (token == null || !token.startsWith("Bearer ")) {
                throw new RuntimeException("无效的 Token");
            }
            String formart_token = token.substring(7); // 去掉 "Bearer " 前缀

            // 2. 解析 JWT
            Claims claims = JwtUtils.parseJWT(formart_token);

            // 3. 获取 userId
            Integer userId = Integer.parseInt(claims.get("userId").toString());

            // 4. 查询考试记录
            PageBean<ExamScoreVO> pageBean = examService.getUserExamScores(userId, page, pageSize);
            return Result.success(pageBean);
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("Token 已过期");
        } catch (SignatureException | MalformedJwtException e) {
            throw new RuntimeException("无效的 Token");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("身份验证失败");
        }


    }
}
